import axios from 'axios'
import { Dialog } from 'vant'
import store from "@/store"
import VueCookies from 'vue-cookies'

axios.defaults.retry = 3
axios.defaults.timeout = 10000

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BDCHATS_API,
  timeout: 50000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
    // config.headers["Content-Type"] = "application/x-www-form-urlencoded"
    var userId = VueCookies.get("userId")
    var token = VueCookies.get("token")
    userId = userId ? userId : store.state.app.userId
    token = token ? token : store.state.app.token
    if (userId && token) {
      if(!config.params) {
        config.params = {}
      }
      config.params.userId = userId;
      config.params.access_token = token;
    }
    // console.log(config)
    return config
}, error => {
    // Do something with request error
    Promise.reject(error)
})
//
// // respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.resultCode !== 1) {
      // -100 Token 过期了;
      if (res.resultCode === 401) {
        localStorage.clear()
        let url = process.env.VUE_APP_BDCHATS_API + '/weixin/auth/login?webCallBack=' + window.location.href
        if(url.indexOf("?") != -1){
            url = url.split("?")[0];
        }
        window.location.href = url
        return Promise.reject("error")
      } else if (res.resultCode === 1030101 || res.resultCode === 1030102) {
        localStorage.clear()
        let url = process.env.VUE_APP_BDCHATS_API + '/weixin/auth/login?webCallBack=' + window.location.href
        if(url.indexOf("?") != -1){
          url = url.split("?")[0];
        }
        // window.location.href = url
        return Promise.reject("error")
      }
      else {
        if(res.resultMsg) {
          Dialog.alert({
            title: "",
            message: res.resultMsg
          }).then(() => {
            // on close
          });
        }
        return response.data
      }
    } else {
      return response.data
    }
  },
  error => {
    var config = error.config
    if (!config || !config.retry) {
      Dialog.alert({
        title: "",
        message: error.message
      }).then(() => {
        // on close
      });
      return Promise.reject(error)
    }
    config.__retryCount = config.__retryCount || 0

    if (config.__retryCount >= config.retry) {
      Dialog.alert({
        title: "",
        message: error.message,
      }).then(() => {
        // on close
      });
      return Promise.reject(error)
    }
    config.__retryCount += 1
    var backoff = new Promise(function(resolve) {
      setTimeout(function() {
        resolve();
      }, config.retryDelay || 1)
    })

    return backoff.then(function() {
      return axios(config);
    })
  }
)

export default service
